<template>
  <div class="outside">
    <div class="app-container" style="width: 92%">
      <inline-form
        ref="InlineForm"
        :item="item"
        @doSubmit="handleDoSubmit"
      ></inline-form>
    </div>
  </div>
</template>

<script>
import _form from "./_form";
import { add, priceAdd } from "./api";
import { addImage } from "../../../../utils/common";
export default {
  data() {
    return {
      item: {
        productName: "",
        productImage: "",
        productImageFile: "",
        productDetailImage: "",
        productDetailImageFile: "",
        jifen: "",
        count: "",
        price: "",
        jifenAndPrice: "",
      },
    };
  },
  methods: {
    async handleDoSubmit() {
      const form = this.$refs.InlineForm;
      if (!form) return;
      form.valid(async (valid) => {
        if (valid) {
          const item = form.obj;
          if (
            item.productImageFile &&
            item.productImageFile !== "" &&
            item.productImageFile !== "img_none"
          ) {
            item.productImage = await addImage(item.productImageFile);
          }
          if (
            item.productDetailImageFile &&
            item.productDetailImageFile !== "" &&
            item.productDetailImageFile !== "img_none"
          ) {
            item.productDetailImage = await addImage(
              item.productDetailImageFile
            );
          }
          delete item.productImageFile;
          delete item.productDetailImageFile;
          const res = await add(item);
          console.log(res, "====>");
          if (res.code === 1) {
            try {
              await priceAdd(res.data, `jifen=${item.jifen}`);
              await priceAdd(res.data, `price=${item.price}`);
              await priceAdd(
                res.data,
                `jifen=${item.jifenAndPrice.split("+")[0]}&price=${
                  item.jifenAndPrice.split("+")[1]
                }`
              );
              this.$message.success("添加成功!");
              this.$router.go(-1);
            } catch (e) {
              console.log(e);
              this.$message.error(e);
            }
          } else {
            this.$message.error(res.msg);
          }
        } else {
          this.$message.error("数据填写错误，请按要求填写!");
        }
      });
    },
  },
  components: {
    "inline-form": _form,
  },
};
</script>

<style scoped></style>
